<template>
  <div class="deviceChangeper">
    <!-- 搜索 -->
    <div class="form_search">
      <el-form :model="formR" @submit.native.prevent>
        <el-input v-model="formR.imei" placeholder="在此输入IMEI编号进行搜索"></el-input>
      </el-form>
      <el-button type="primary" slot="append" @click="condition" class="dev_search">搜索</el-button>
      <el-button type="primary" slot="append" @click="handleExport" class="dev_search">导出</el-button>
    </div>
    <!-- 表单列表 -->
    <div class="device-manage">
      <el-table :data="listData" stripe :header-cell-style="getRowClass" v-loading="loading">
        <el-table-column prop="num" label="序号" ></el-table-column>
        <el-table-column prop="imei" label="IMEI号"></el-table-column>
        <el-table-column prop="devname" label="设备类型">
          <template slot-scope="scope">
            <!-- <div style="display: inline;" v-if="scope.row.devname =='fireplug'">消防栓</div> -->
            <div style="display: inline;" v-if="scope.row.devname =='scm'">烟感设备</div>
          </template>
        </el-table-column>
        <el-table-column prop="areaName" label="设备安装区域"></el-table-column>
        <el-table-column prop="equip_site_address[0]" label="设备安装地址"></el-table-column>
        <el-table-column prop="equip_site_address[1]" label="设备安装位置"></el-table-column>
        <el-table-column prop="dev_equip_time" label="安装时间">
          <template slot-scope="scope">
            <div>{{formateEquipTime(scope.row.dev_equip_time)}}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small"  title="更换设备"  v-has-permission="'change_replace'" @click="handelChange(scope.row)" style='padding-left:0'>
              <img src="../../../../../static/image/device/change.png">
            </el-button>-->
            <!-- <el-button type="text" size="small" title="修改地址"
              v-has-permission="'change_edit'"
            @click="handelEdit(scope.row)" style='margin-left:0'>
              <img src="../../../../../static/image/device/edit.png">
            </el-button>-->
            <el-button type="text" size="small" title="查看" @click="handelSee(scope.row)" v-has-permission="'changep_query'">
              <img src="../../../../../static/image/device/see.png">
            </el-button>
            <!-- <el-button type="text" size="small" title="删除" @click="handleDelete(scope.row)"   v-has-permission="'changep_delete'" >
              <img src="../../../../../static/image/device/delect.png">
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <page-list
        :size.sync="dev_pageSize"
        :total="totals"
        :current.sync="dev_currentPage"
        @change="getListData"
      ></page-list>
      <!-- Form 弹框查看 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="title"
        :visible.sync="dialogTableVisible"
        :modal-append-to-body="false"
        class="dialog-seechange"
      >
        <el-form :model="form" @submit.native.prevent>
          <el-form-item label="设备编号：" v-if="showImei">{{form.imei}}</el-form-item>
          <el-form-item label="设备编号：" v-if="!showImei" class="changesImei">
            <el-input v-model="form.imei"></el-input>
          </el-form-item>
          <el-form-item label="安装区域：">{{form.areaName}}</el-form-item>
          <el-form-item label="详细地址：">{{siteAddress}}</el-form-item>
          <el-form-item label="详细位置：">{{siteName}}</el-form-item>
          <el-form-item label="安装时间：">{{formateEquipTime(form.dev_equip_time)}}</el-form-item>
        </el-form>
        <div slot="footer" style="text-align: center;" v-if="seeImei">
          <el-button
            style="padding: 5px 25px;background-color: rgb(178, 186, 211);border-color:rgb(178,186,211);color:rgb(255, 255, 255);"
          >取 消</el-button>
          <el-button
            type="primary"
            style="padding: 5px 25px;background-color:#EB3838;border-color:#EB3838;"
          >确 定</el-button>
        </div>
      </el-dialog>

      <!--按照时间段导出保单-->
      <el-dialog title="批量导出" :visible.sync="exportDialogVisible" :close-on-press-escape="false"
                 :close-on-click-modal="false" width="456px" class="center">
        <div class="device-list">
          <el-form :model="exportForm" ref="ruleForm" label-width="100px">
            <el-form-item label="开始时间：">
              <el-form-item prop="startTime">
                <el-date-picker prefix-icon="" type="datetime" placeholder="选择日期" v-model="exportForm.startTime"
                                @change="handleStartChange" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-form-item>
            <el-form-item label="结束时间：">
              <el-form-item prop="endTime">
                <el-date-picker prefix-icon="" type="datetime" placeholder="选择日期" v-model="exportForm.endTime"
                                @change="handleEndChange" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button @click="exportDialogVisible = false" class="cancel-btn function-btn">取  消</el-button>
            <el-button type="primary" class="function-btn" @click.stop="sure">确  定</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 修改信息 -->
      <!-- <el-dialog
        :close-on-click-modal="false"
        :title="title"
        :visible.sync="dialogFormVisible"
        :modal-append-to-body="false"
        class="dialog-seechange">
        <el-form :model="form" @submit.native.prevent>
          <el-form-item label="位置编号：">{{form.dev_equip_id}} </el-form-item>
          <el-form-item label="设备编号：">{{form.imei}}</el-form-item>
          <el-form-item label="区域名称：">
             <el-input v-model="form.imei" ></el-input>
          </el-form-item>
          <el-form-item label="场所名称：">
             <el-input v-model="form.imei" ></el-input>
          </el-form-item>
          <el-form-item label="详细地址：">
            <el-input v-model="form.imei" ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer"  style="text-align: center;" >
          <el-button style='padding: 5px 25px;background-color: rgb(178, 186, 211);border-color:rgb(178,186,211);color:rgb(255, 255, 255);'>取 消</el-button>
          <el-button type="primary" style="padding: 5px 25px;background-color:#EB3838;border-color:#EB3838;">确 定</el-button>
        </div>
      </el-dialog>-->

      <!-- 删除提示 -->
      <!-- <delete-dialog :is-show="deleteDialogShow" :desc="desc" @close="handleClose"></delete-dialog> -->
    </div>
  </div>
</template>

<script>
import Config from "@/config";
import { regionDataPlus } from 'static/js/regionData';
import { mapGetters } from "vuex";
import moment from "moment";
import { log } from "util";
import PageList from "@/components/PageList";
// import DeleteDialog from '../../../../components/CommonDialog'
export default {
  name: "DeviceChangeP",
  components: {
    PageList,
    // DeleteDialog

  },
  data() {
    return {
      ops: {
        bar: {
          background: "#DDDEE0"
        }
      },
      // 查询
      formR: {},
      // 列表分页
      totals: 0,
      dev_currentPage: 1,
      dev_pageSize: 15,
      inputs: 15,
      //列表
      listData: [],
      // loading
      loading: true,
      // 查看
      dialogTableVisible: false,
      showImei: true,
      seeImei: true,
      // 弹框名称
      title: "",
      //弹框数据
      form: {},
      // 删除弹框
      deleteDialogShow:false,
      deleteObject: {},
      desc: '',
      //修改信息弹框
      dialogFormVisible: false,
      siteAddress :'',
      siteName :'',

      // 导出保单弹框
      exportDialogVisible: false,
      warrantyBatch: [],
      exportForm: {
        startTime: undefined,
        endTime: undefined,
      },
      // 行业，投保人类型Map
      industryMap: null,
      insuredTypeMap: null,
    };
  },
  methods: {
    formateEquipTime (time) {
      if (!time) {
        return ''
      }
      return time.replace(/T/, ' ')
    },
    // 表头添加背景颜色
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background:#f6f6f6";
      } else {
        return "";
      }
    },
    // 获取列表
    getListData() {
      var params = {};
      this.loading = true;
       if (this.district.districtType === 1) {
       params.country = '86';
      }else if (this.district.districtType === 2) {
        params.province = this.district.provinceCode;
      } else if(this.district.districtType === 3) {
        params.city = this.district.cityCode;
      }

      params.imei = this.formR.imei ? this.formR.imei : undefined;
      let url = `${
        Config.DEVICE_MANAGE_URL
      }/inventory/device_equiped_list?page=${this.dev_currentPage - 1}&size=${
        this.dev_pageSize
      }&devtype=nbiot&devname=scm&subtype=individual`;

      this.$http.get(url, params).then(res => {
        this.totals = res.allcount;
        if(res.array.length){
          res.array.map((item, i) => {
            if (this.dev_currentPage === 1) {
              item.num = i + 1;
            } else {
              item.num = (this.dev_currentPage - 1) * this.dev_pageSize + i + 1;
            }
            this.handleData(item);
            item.update_time = moment(item.update_time).format("YYYY-MM-DD HH:mm:ss");
            item.equip_site_address = item.equip_site_address ? item.equip_site_address.split('/') : ''
          });
          this.listData = res.array;
          this.loading = false;
        }else{
          this.listData = res.array;
          this.loading = false;
        }
      }).catch(e =>{
        this.listData = res.array;
        this.loading = false;
      })
    },
    condition(){
      this.dev_currentPage  = 1;
      this.getListData();
    },
    /**
     * 导出excel
     */
    handleExport () {
      this.exportForm = this.$options.data().exportForm
      this.exportDialogVisible = true
    },
    handleStartChange () {
      this.days = 0
      if (!this.exportForm.startTime) {
        return
      }
      const now = new Date().getTime()
      if (this.exportForm.endTime) {
        if (this.exportForm.startTime.getTime() > this.exportForm.endTime.getTime()) {
          this.$message({
            message: '开始时间不能大于结束时间',
            type: 'warning'
          })
          this.exportForm.startTime = null
        }
      }
      if (this.exportForm.startTime && this.exportForm.startTime.getTime() > now) {
        this.$message({
          message: '开始时间不能大于当天',
          type: 'warning'
        })
        this.exportForm.startTime = null
      }
      console.log(this.exportForm)
    },
    handleEndChange () {
      this.days = 0
      if (!this.exportForm.endTime) {
        return
      }
      if (this.exportForm.startTime) {
        if (this.exportForm.startTime.getTime() > this.exportForm.endTime.getTime()) {
          this.$message({
            message: '结束时间不能小于开始时间',
            type: 'warning'
          })
          this.exportForm.startTime = null
        }
      }
      console.log(this.exportForm)
    },
    /**
     * 初始化类型Map对象
     * */
    initTypeMap () {
      this.industryMap = new Map()
      this.industryMap.set('1', '普通')
      this.industryMap.set('2', '仓储')
      this.industryMap.set('3', '易燃、易爆')
      this.insuredTypeMap = new Map()
      this.insuredTypeMap.set('1', '个人')
      this.insuredTypeMap.set('2', '商户')
    },
    sure () {
      if (!this.exportForm.startTime) {
        this.$message({
          message: '请选择开始时间',
          type: 'warning'
        })
        return
      }
      if (!this.exportForm.endTime) {
        this.$message({
          message: '请选择结束时间',
          type: 'warning'
        })
        return
      }
      const startTime = this.getTimeString(this.exportForm.startTime)
      const endTime = this.getTimeString(this.exportForm.endTime)
      const params = this.getParams({startTime, endTime})
      this.createExport(params)
      this.exportDialogVisible = false
    },
    /**
     * 构造查询参数
     * */
    getParams (params) {
      const defaultParams = {
        startTime: '',
        endTime: ''
      }
      return {...defaultParams, ...params}
    },
    async createExport (params) {
      const deviceC = await this.getExportData(params)
      if (!deviceC.length) {
        this.$message.error('查询设备失败')
        return
      }

      const exportData = this.createXlsxJsonData(deviceC)
      const filename = this.getXlsxName(params)
      this.export2Xlsx(exportData, filename)
    },
    /**
     * 根据时间段下载所有设备数据
     * TODO 等接口
     */
    getExportData(opt) {
      var params = {};
      this.loading = true;
      if (this.district.districtType === 1) {
        params.country = '86';
      }else if (this.district.districtType === 2) {
        params.province = this.district.provinceCode;
      } else if(this.district.districtType === 3) {
        params.city = this.district.cityCode;
      }

      params.imei = this.formR.imei ? this.formR.imei : undefined;
      let url = `${Config.DEVICE_MANAGE_URL}/inventory/device_equiped_list?page=0&size=1000000&devtype=nbiot&devname=scm&subtype=individual`;
      url += `&equip_time_start=${opt.startTime}&equip_tme_end=${opt.endTime}`

      return new Promise((resolve, reject) => {
        this.$http.get(url, params)
          .then(res => {
            this.loading = false;
            if(res.array.length){
              res.array.map((item, i) => {
                this.handleData(item);
                item.update_time = moment(item.update_time).format("YYYY-MM-DD HH:mm:ss");
                item.equip_site_address = item.equip_site_address ? item.equip_site_address.split('/') : ''
              });
              resolve(res.array);
            }else{
              resolve([])
            }
          })
          .catch(e =>{
            resolve([])
            this.loading = false;
          })
      })


    },
    /**
     * 获取时间字符串 '2019-01-01'
     * @param date {Date}
     * @return String
     * */
    getTimeString (date) {
      const util = this.$util.Date
      return `${util.getYear(date)}-${util.getMonth(date)}-${util.getDate(date)} ${util.getHours(date)}:${util.getMinutes(date)}:${util.getSeconds(date)}`
    },
    getXlsxName (params) {
      let title = '设备变更C端-'
      if (params.startTime && params.endTime) {
        title += `${params.startTime}至${params.endTime}`
      }
      return title
    },
    /**
     * 构造xlsx用json导出excel的json
     * */
    createXlsxJsonData (arr) {
      const temp = []
      // 处理excel标题
      const key = [
        '序号',
        'IMEI号',
        'ICCID号',
        '设备类型',
        '设备安装区域',
        '设备安装地址',
        '安装位置',
        '安装时间',

        '归属人',
        '归属人电话',
        '营业执照/身份证号',
        '保险单号',
        '被保人行业',
        '投保日期',
        '生效日期',
        '到期日期',
      ]
      temp.push(key)
      // 处理excel内容
      arr.forEach((item, index) => {
        temp.push([
          index + 1,
          item.imei,
          item.iccid,
          item.devname =='scm' ? '烟感设备' : '消防栓',
          item.areaName,
          item.equip_site_address[0],
          item.equip_site_address[1],
          item.update_time,

          item.user_name,
          item.user_phone,
          item.insurance_id_number,
          item.insurance_id,
          item.insurance_industry,
          item.insurance_create_time,
          item.insurance_effective_time,
          item.insurance_expire_time,
        ])
      })

      return temp
    },
    /**
     * 批量导出
     * */
    export2Xlsx (data, name = '保单') {
      /* original data */
      var filename = `${name}.xlsx`;
      // var data = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar",new Date("2014-02-19T14:30Z"), "0.3"], ["baz", null, "qux"]]
      var ws_name = "SheetJS";

      if(typeof console !== 'undefined') console.log(new Date());
      var wb = XLSX.utils.book_new(), ws = XLSX.utils.aoa_to_sheet(data);

      /* add worksheet to workbook */
      XLSX.utils.book_append_sheet(wb, ws, ws_name);

      /* write workbook */
      if(typeof console !== 'undefined') console.log(new Date());
      XLSX.writeFile(wb, filename);
      if(typeof console !== 'undefined') console.log(new Date());
    },
    /**
     * 对展示数据进行预处理
     * */
    handleData (item) {
      const province = this.getAreaObj(regionDataPlus, item.province)
      if (item.city === '419000' || item.district === '419001' || item.district === '济源市') {
        item.areaName = `${province.label}济源市`
      } else {
        try {
          const city = this.getAreaObj(province.children, item.city)
          const district = item.district ? this.getAreaObj(city.children, item.district) : {label: ''}
          item.areaName = `${province.label}${city.label}${district.label}`
        } catch (e) {
          item.areaName = '-----'
        }

      }
    },
    /**
     * 获取区域信息
     * @param {Array} arr
     * @param {String} value
     * @return {Object} obj
     * */
    getAreaObj(arr, value) {
      return arr.find(res => res.value === value);
    },
    // 查看
    handelSee(data) {
      console.log(data)
      for (var i in data) {
        this.form[i] = data[i];
      }
      this.siteAddress = data.equip_site_address[0]
      this.siteName = data.equip_site_address[1]
      this.form.update_time = moment(this.form.update_time).format( "YYYY-MM-DD HH:mm:ss" );
      this.title = "预览";
      this.dialogTableVisible = true;
      this.showImei = true;
      this.seeImei = false;
    },
    //更改iemi
    /**
     *
    handelChange (data) {
      this.form = JSON.parse(JSON.stringify(data))
      this.title = "更换设备";
      this.dialogTableVisible = true;
      this.showImei = false
      this.seeImei = true
    },
     */
    //修改信息
    /**
    *
    handelEdit(data){
      this.form = JSON.parse(JSON.stringify(data))
      this.title = "地址修改";
      this.dialogFormVisible = true;
    },
    */

    //删除

    /**
    *
    * handleDelete(data) {
      // console.log(data)
      let url = `${
        Config.DEVICE_MANAGE_URL
      }/device_modify_history/count_by_action_imei`;
      let param = {
        user_id: this.user.id,
        action_name: "unbind"
      };
      this.$http.get(url, param).then(res => {
        // console.log(res)
        if (res.count <= 20) {
          this.deleteObject = data;
          this.desc = `确定要删除${data.imei}吗？`;
          this.deleteDialogShow = true;
        } else {
          this.$message({
            message:
              "您已删除超过20个设备,已通知主运营公司管理员,如需删除设备，请于明天再进行删除操作。",
            type: "error"
          });
        }
      });
    },
    handleClose(id) {
      this.deleteDialogShow = false;
      if (!id) {
        this.deleteObject = {};
        return;
      }
      let url = `${Config.DEVICE_MANAGE_URL}/inventory/device_unbind`;
      let param = {
        devtype: this.deleteObject.devtype,
        devname: this.deleteObject.devname,
        id: this.deleteObject.id,
        imei: this.deleteObject.imei,
        user_id: this.deleteObject.id,
        subtype: this.deleteObject.subtype
      };
      this.$http
        .post(url, param)
        .then(res => {
          this.deleteObject = {};
          this.$message.success("删除设备变更信息成功！");
          this.getListData();
        })
        .catch(e => {
          this.deleteObject = {};
          this.$message({
            message: "删除设备变更信息失败！",
            type: "error"
          });
        });
    }
    */
  },
  created() {
    this.getListData();
    this.initTypeMap()
  },
  computed: {
    ...mapGetters("user", {
      module: "dealedModule",
      user: "getUser",
      role: "getRole",
      district: "getDistrict"
    })
  }
};
</script>

<style lang='scss' >
@import "../../../../../static/scss/common";
.deviceChangeper {
  width: 100%;
  height: 100%;
  // 搜索
  .form_search {
    width: 100%;
    height: 42px;
    .el-form {
      width: 500px;
      float: left;
      height: 42px;
      line-height: 42px;
      box-shadow: 5px 5px 0px 0px rgba(34, 34, 34, 0.1);
      border: 0;
      .el-input {
        .el-input__inner {
          height: 42px;
          border-radius: 0;
          border: 0;
          line-height: 42px;
        }
        .el-input__inner:hover {
          border-color: 0;
        }
      }
    }
    .dev_search {
      width: 80px;
      height: 42px;
      background: rgba(235, 56, 56, 1);
      box-shadow: 5px 5px 0px 0px rgba(34, 34, 34, 0.1);
      padding: 0;
      border-radius: 0;
      font-size: 14px;
    }
  }
  //列表
  .device-manage {
    width: 100%;
    height: auto;
    background: $white;
    margin-top: 24px;
    .export {
      height: 24px;
      line-height: 24px;
      margin-right: 27px;
      text-align: right;
      padding-top: 12px;
    }
    // 查看
    .dialog-seechange.el-dialog__wrapper {
      .el-dialog {
        width: 420px;
        height: 300px;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto !important;
        .el-dialog__body {
          .el-form {
            .el-form-item {
              .el-form-item__label {
                line-height: 36px;
              }
              .el-form-item__content {
                line-height: 36px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
            //更换设备
            .el-form-item.changesImei {
              .el-form-item__content {
                line-height: 32px;
                .el-input {
                  .el-input__inner {
                    height: 32px;
                    line-height: 32px;
                    width: 260px;
                    border-radius: 0;
                  }
                }
              }
            }
          }
        }
        .el-dialog__footer {
          padding: 30px 0;
          background: $white;
        }
      }
    }
    // 导出
    .center /deep/ .el-dialog {
      padding-bottom: 32px;
    }
    .device-list {
      & /deep/ .el-table {
        padding: 0 !important;
      }
      .device {
        width: 280px;
        height: 50px;
        background: rgba(255,255,255,1);
        box-shadow: 0px 3px 7px 0px rgba(204, 204, 204, 0.35);
        font-size: 18px;
        color: #EB3838;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      & /deep/ .el-input--prefix .el-input__inner {
        padding-left: 30px;
      }
      .days {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 24px 0 40px;
        .day {
          width: 72px;
          height: 32px;
          line-height: 32px;
          text-align: center;
          box-sizing: border-box;
          border: 1px solid #D9D9D9;
          color: #333;
          font-size: 12px;
          border-radius: 4px;
          cursor: pointer;
        }
        .selected {
          background-color: #eb3838;
          color: #fff;
        }
      }
      .btns {
        text-align: center;
        margin-top: 40px;
      }
    }
    // 删除
    .el-dialog__wrapper.btndelete {
      .el-dialog {
        width: 380px;
        height: 182px;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto !important;
        .el-dialog__header {
          .el-dialog__title {
            font-size: 14px;
            line-height: 0;
            color: #303133;
            float: left;
          }
          .el-dialog__headerbtn {
            top: 12px;
          }
        }
        .el-dialog__body {
          border: 0;
          padding-top: 0;
        }
      }
    }
  }
}
</style>
